import { observable, action, useStrict, computed, asMap, toJS } from 'mobx';
import FieldEntity from './FieldEntity';
import {_, FieldUtil} from '../util/pcPublic';
import * as API from '../apis/form';
import { Browser } from 'weaver-mobile-page';
import base from '../util/base';
import BaseStore from './BaseStore';

export default class DetailEntity extends BaseStore{
    attr = {};
    fieldInfo = {};
    addRowDefValue = {};
    addDefaultCopy = false;
    @observable indexnum = 0;
    @observable deldtlid = "";
    @observable detailData = observable.map ? observable.map({}) : asMap({});
    @observable rowInfo = observable.map ? observable.map({}) : asMap({});
    @observable pagingInfo = {enabled:false};
    @observable dropBtnKey = 1;
    @observable sapBtnStore = new Browser.Store({id:"fieldSapMulti", route:"/req"});
    //获取排序后的行信息
    @computed get rowInfoArr(){
        let arr = [];
        this.rowInfo.forEach((info,rowKey) =>{
            let _info = toJS(info);
            _info["rowIndex"] = parseInt(rowKey.substring(4));
            arr.push(_info);
        });
        arr.sort((a,b) =>{
            return a.rowIndex - b.rowIndex;
        });
        //排序完成后计算序号
        arr.map((_info,index) =>{
            _info["serialNum"] = index+1;
        });
        return arr;
    }
    //获取所有行的行标拼接成串
    @computed get allRowIndexStr(){
        let str = "";
        this.rowInfoArr.map((item,index) =>{
            str += `${index>0 ? "," : ""}${item.rowIndex}`;
        })
        return str;
    }
    //获取当前页显示的行信息
    @computed get currentPageRowArr(){
        const rowInfoArr = this.rowInfoArr;
        const { enabled,current,pagesize } = this.pagingInfo;
        if(enabled){
            const begin = (current - 1) * pagesize;
            return rowInfoArr.slice(begin, begin + pagesize);
        }else{
            return rowInfoArr;
        }
    }
    //获取当前页所有行的行标拼接成串
    @computed get currentPageRowIndexStr(){
        let str = "";
        this.currentPageRowArr.map((item,index) =>{
            str += `${index>0 ? "," : ""}${item.rowIndex}`;
        })
        return str;
    }
    //计算配置行合并字段的合并信息
    @computed get currentPageRowMergeInfo(){
        let mergeResult = observable.map ? observable.map({}) : asMap({});
        const { isedit,mergefields } = this.attr;
        const mergeFieldArr = _.trim(mergefields).split(",").filter(item => item !== "");
        if(mergeFieldArr.length === 0 || this.currentPageRowArr.length === 0)
            return mergeResult;
        const { commonParam } = base.wfGlobalStore;
        const pageViewOnly = parseInt(commonParam.isviewonly || 0) === 1 || parseInt(commonParam.isaffirmance || 0) === 1;
        mergeFieldArr.forEach(fieldid =>{
            if(!(fieldid in this.fieldInfo))
                return true;
            const fieldAttr = this.fieldInfo[fieldid];
            if(fieldAttr.htmltype === 6)
                return true;
            //第一步：算只读属性、字段值
            let mergeInfo = [];
            this.currentPageRowArr.forEach(rowInfo =>{
                const { rowIndex,keyid } = rowInfo;
                const fieldMark = `field${fieldid}_${rowIndex}`;
                const fieldObj = this.detailData.has(fieldMark) ? this.detailData.get(fieldMark) : null;
                //算字段是否只读
                let fieldViewOnly = pageViewOnly || rowViewOnly;
                if(!fieldViewOnly){
                    let viewAttr_tmp = -1;
                    if(fieldObj !== null && fieldObj.variable.has("viewAttr"))
                        viewAttr_tmp = parseInt(fieldObj.variable.get("viewAttr")) || 0;
                    fieldViewOnly = viewAttr_tmp > 0 ? viewAttr_tmp === 1 : fieldAttr.viewattr === 1;
                }
                //算字段值
                const rowViewOnly = isedit !== 1 && parseInt(keyid || 0) > 0;
                let fieldValue = fieldObj === null ? "" : fieldObj.value;
                if(fieldAttr.htmltype === 4)
                    fieldValue = fieldValue == "1";     //check框类型1选中其它均为未选中
                mergeInfo.push({rowIndex, fieldValue, fieldViewOnly});
            });
            //第二步，reduce算法比较得出合并结果
            mergeInfo.reduce((pre,cur,index) =>{
                const isSame = pre.fieldViewOnly === true && cur.fieldViewOnly === true && pre.fieldValue !== "" && pre.fieldValue === cur.fieldValue;
                const fieldKey = `field${fieldid}`;
                const preRow = mergeResult.get(`row_${pre.rowIndex}`) || {};
                const curRow = mergeResult.get(`row_${cur.rowIndex}`) || {};
                let preRowSpan = index === 1 ? 1 : preRow[fieldKey];
                let curRowSpan = 1;
                if(isSame){
                    preRowSpan++;
                    curRowSpan = 0;
                }
                mergeResult.set(`row_${pre.rowIndex}`, {...preRow, ...{[fieldKey]:preRowSpan}});
                mergeResult.set(`row_${cur.rowIndex}`, {...curRow, ...{[fieldKey]:curRowSpan}})
                return isSame ? pre : cur;
            });
        });
        return mergeResult;
    }

    constructor(attr={}, fieldInfo={}){
        super();
        this.attr = attr;
        this.fieldInfo = fieldInfo;
        if(attr.isopenpaging === 1){
            this.pagingInfo = {
                enabled: true,
                current: 1,
                pagesize: attr.pagesize
            };
        }
    }

    @action('初始化明细已有行数据')
    initDetailData = (data) =>{
        this.addRowDefValue = data.addRowDefValue || {};
        this.indexnum = data.indexnum;
        !_.isEmpty(data.rowDatas) && _.forIn(data.rowDatas, (rowData,rowKey) =>{
            this.convertSetRowData(rowKey.substring(4), rowData);
        });
    }

    @action('指定行记录选中/不选中')
    controlRowChecked = (rowIndexStr, checked=false) =>{
        rowIndexStr.split(",").map(rowid =>{
            if(this.rowInfo.has(`row_${rowid}`)){
                const info = this.rowInfo.get(`row_${rowid}`);
                let rowChecked = checked;
                if(this.dropBtnKey === 1 && this.attr.isdelete !== 1 && parseInt(info.get("keyid") || 0) > 0)    //已有明细行禁止选中
                    rowChecked = false;
                if(info.get("disableCheck") === true)
                    rowChecked = false;
                info.set("checked", rowChecked);
            }
        });
    }

    @action('清除所有行记录的选中状态')
    clearAllRowChecked = () =>{
        this.controlRowChecked(this.allRowIndexStr, false);
    }

    @action('控制明细行属性对象')
    controlDetailRowAttr = (obj={}) =>{
        Object.keys(obj).map(rowKey =>{
            if(!this.rowInfo.has(rowKey))
                return true;
            const info = this.rowInfo.get(rowKey);
            const addAttr = obj[rowKey] || {};
            _.forIn(addAttr, (v,k) =>{
                info.set(k, v);
            });
        });
    }

    @action('新增明细行')
    add_Row = (initData={}, fromLinkage=false, isCopy=false) =>{
        let rowData = _.cloneDeep(this.addRowDefValue);
        //联动含初始值情况
        _.forIn(initData, (v,k) =>{
            if(k.indexOf("field") > -1){
                rowData[k] = v;
            }
        });
        //新增行同时复制指定行数据
        if(!fromLinkage && !isCopy && this.addDefaultCopy){
            const lastRowIndex = this.rowInfoArr.length > 0 ? this.rowInfoArr[this.rowInfoArr.length-1].rowIndex : -1;
            lastRowIndex > -1 && _.forIn(this.fieldInfo, (v,k)=>{
                if(this.detailData.has(`field${k}_${lastRowIndex}`))
                    rowData[`field${k}`] = this.detailData.get(`field${k}_${lastRowIndex}`).valueObj;
            });
        }
        this.jumpLastPage();
        this.convertSetRowData(this.indexnum, rowData, fromLinkage);
        this.indexnum = parseInt(this.indexnum) + 1;
    }

    @action('删除明细行')
    del_Row = (arr=[]) =>{
        let delRowKeys = "";
        arr.map(rowIndex =>{
            const info = this.rowInfo.get(`row_${rowIndex}`);
            //已有数据行记录删除行key
            if(info.has("keyid") && parseInt(info.get("keyid")) > 0)  
                delRowKeys += ","+ info.get("keyid");
            this.rowInfo.delete(`row_${rowIndex}`);
            //清除被删除行数据
            _.forIn(this.fieldInfo, (v,k)=>{
                const fieldMark = `field${k}_${rowIndex}`;
                //删除时需触发被删除字段的绑定事件
                window.WfForm.triggerFieldBindEvent(fieldMark, "");
                this.detailData.delete(fieldMark);
            });
        });
        if(delRowKeys !== "")    
            delRowKeys = delRowKeys.substring(1);
        this.deldtlid = this.deldtlid === "" ? delRowKeys : `${this.deldtlid},${delRowKeys}`;
        //分页情况，删除完如果无数据，跳转至前一页
        if(this.pagingInfo.enabled && this.currentPageRowArr.length === 0 && this.rowInfoArr.length > 0){
            this.jumpLastPage(false);
        }
    }

    @action('行数据转换并赋值')
    convertSetRowData = (rowIndex, rowData={}, fromLinkage=false) =>{
        let info = observable.map ? observable.map({}) : asMap({});
        info.set("fromLinkage", fromLinkage);
        !_.isEmpty(rowData) && _.forIn(rowData, (v,k) =>{
            if(k.indexOf("field") > -1){
                const fieldid = k.substring(5);
                if(fieldid in this.fieldInfo) {   //限制属于本明细的字段
                    const newValue = FieldUtil.convertValueBeforeChangeStore(v.value, this.fieldInfo[fieldid]);
                    v = {...v, value: newValue};
                    this.detailData.set(`${k}_${rowIndex}`, new FieldEntity(`${k}_${rowIndex}`, v));
                }
            }else
                info.set(k, v);
        });
        this.rowInfo.set(`row_${rowIndex}`, info);
    }

    @action('设置新增是否默认复制数据')
    setAddDefaultCopy = (bool=false) =>{
        this.addDefaultCopy = bool;
    }

    @action('控制分页信息')
    controlPagingInfo = (params={}) =>{
        this.pagingInfo = {...this.pagingInfo, ...params};
    }

    @action('改变每页条数')
    changePageSize = (params={}) =>{
        if(this.pagingInfo.pagesize === params.pagesize)
            return;
        this.clearAllRowChecked();
        this.controlPagingInfo({pagesize:params.pagesize, current:1});
        API.saveDetailPaging(params);
    }

    @action('跳转至最后一页')
    jumpLastPage = (needAddOne=true) =>{
        const { enabled,current,pagesize } = this.pagingInfo;
        if(enabled){
            let total = this.rowInfoArr.length;
            if(needAddOne)
                total++;
            const last = Math.ceil(total/pagesize);
            this.controlPagingInfo({current:last});
        }
    }

    @action('切换按钮')
    setDropBtnKey = (key) =>{
        this.clearAllRowChecked();
        this.dropBtnKey = key;
    }

}